package com.nabaixin.qr.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;

public class HttpUtil {
	/**
	 * 发送请求
	 * @param url
	 * @param method
	 * @param params
	 * @param enc
	 * @return
	 */
	public static String openUrl(String url, String method, Bundle params, String enc){
		
		String response = null;
		//GET请求
		if(method.equals("GET")){
			if(params != null)
				url = url + "?" + encodeUrl(params);
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent"));
			conn.setReadTimeout(10000); //设置超时时间
			if(method.equals("POST")){
				conn.setRequestMethod("POST");
				conn.setDoOutput(true);
				if(params != null)
					conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
			}
			response = read(conn.getInputStream(),enc);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}
	/**
	 * 读取输入流，转换为String
	 * @param in
	 * @param enc
	 * @return
	 * @throws IOException
	 */
	private static String read(InputStream in, String enc) throws IOException {
		StringBuilder sb = new StringBuilder();
		BufferedReader r = null;
		if(enc != null){
			//按指定的编码读入流
			r = new BufferedReader(new InputStreamReader(in,enc), 1000);
		}else{
			//按默认的编码读入
			r = new BufferedReader(new InputStreamReader(in), 1000);
		}
		for (String line = r.readLine(); line != null; line = r.readLine()) {
			sb.append(line);
		}
		in.close();
		return sb.toString();
	}
	/**
	 * 按key-Value的方式组拼请求参数
	 * 参数内通过“=”连接，参数间通过“&”来连接
	 * @param parameters
	 * @return
	 */
	public static String encodeUrl(Bundle parameters) {
		if (parameters == null)
			return "";
		StringBuilder sb = new StringBuilder();
		//因为第一个参数和URL之间是通过"?"来连接的
		boolean first = true;
		for (String key : parameters.keySet()) {
			if (first)
				first = false;
			else
				sb.append("&");
			sb.append(key + "=" + parameters.getString(key));
		}
		return sb.toString();
	}
	/**
	 * 把数据post到服务器，获取返回的结果
	 * 
	 * @param uriAPI
	 *            ： API 所在的路径
	 * @param params
	 *            ： 传递的数据
	 */
	public static String postToServer(String uriAPI, List<NameValuePair> params) {
		/* 建立HTTPost对象 */
		HttpPost httpRequest = new HttpPost(uriAPI);
		
		try {
			/* 添加请求参数到请求对象 */
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			/* 发送请求并等待响应 */
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequest);
			/* 若状态码为200 ok */
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				/* 读返回数据 */
				return EntityUtils.toString(httpResponse.getEntity());

			} else {
				return "Error Response: "
						+ httpResponse.getStatusLine().toString();
			}
		} catch (Exception e) {
			return "post failure :caused by-->" + e.getMessage().toString();
		}

	}
}
